﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using WidgetsDesign.API.Models;
using WidgetsDesign.API.Services;
using static WidgetsDesign.API.Controllers.UserController;

[Route("api/[controller]/[action]")]
[ApiController]
public class UploadFileController : ControllerBase
{
    private readonly IWebHostEnvironment _webHostEnvironment;
    private readonly IUserRepository _userRepository;
    private readonly IUploadFileRepository _uploadFileRepository;
    private readonly IMapper _Mapper;
    private readonly ITrainRepository _trainRepository;
    private readonly IMeetingRepository _meetingRepository;

    private IConfiguration _configuration { get; set; }
    public UploadFileController(IUserRepository userRepository, IMapper mapper, IConfiguration config, IWebHostEnvironment webHostEnvironment, IUploadFileRepository uploadFileRepository, ITrainRepository trainRepository, IMeetingRepository meetingRepository)
    {
        _configuration = config;
        _webHostEnvironment = webHostEnvironment;
        _userRepository = userRepository;
        _Mapper = mapper;
        _uploadFileRepository = uploadFileRepository;
        _trainRepository = trainRepository;
        _meetingRepository = meetingRepository;
    }
    [HttpPost("{UserId}")]
    public async Task<IActionResult> UploadFile(IFormFile formFile, [FromRoute] int UserId)
    {

        var UserInfo = await _userRepository.GetUserInfoById(UserId);
        if (UserInfo == null)
        {
            return Ok(new { code = 0, message = "不存在该用户" });
        }
        var fileSize = formFile.Length;
        if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
        {
            return Ok(new { code = 0, message = "上传的文件不能大于10M" });
        }
        var currentDate = DateTime.Now;
        var fileExtension = Path.GetExtension(formFile.FileName);//获取文件格式，拓展名
        var saveName = UserId + "_" + currentDate.ToString("yyMMddHHmmss") + currentDate.Millisecond.ToString() + fileExtension;
        string web_path = _webHostEnvironment.WebRootPath;
        string folderPath = Path.Combine("wwwroot", "Images");

        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }
        string path = Path.Combine(folderPath, saveName);
        using (var fs = System.IO.File.Create(path))
        {
            await formFile.CopyToAsync(fs);
            await fs.FlushAsync();
        }
        var newFile = new UploadFile
        {
            Uuid = Guid.NewGuid(),
            UserId = UserId,
            CreateTime = DateTime.Now,
            FileUrl = "Images/" + saveName,
            FileSize = fileSize,
        };
        _uploadFileRepository.CreateFile(newFile);
        await _uploadFileRepository.SaveAsync();
        return Ok(new { code = 200, message = newFile.Uuid });
    }

    /// <summary>
    /// 上传头像
    /// </summary>
    /// <param name="formFile"></param>
    /// <param name="UserId"></param>
    /// <returns></returns>
    [HttpPost("{uuid}")]
    public async Task<IActionResult> UploadAvatar(IFormFile formFile, [FromRoute] Guid uuid)
    {
        var UserInfo = await _userRepository.GetUserInfoByUuid(uuid);
        if (UserInfo == null)
        {
            return Ok(new { code = 0, message = "不存在该用户" });
        }
        var fileSize = formFile.Length;
        if (fileSize > 1024 * 1024 * 2) //2M TODO:(1mb=1024X1024b)
        {
            return Ok(new { code = 0, message = "上传的文件不能大于5M" });
        }
        var currentDate = DateTime.Now;
        var fileExtension = Path.GetExtension(formFile.FileName);//获取文件格式，拓展名
        var saveName = uuid + fileExtension;
        string web_path = _webHostEnvironment.WebRootPath;
        string folderPath = Path.Combine("wwwroot", "Avatar");

        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }
        string path = Path.Combine(folderPath, saveName);
        using (var fs = System.IO.File.Create(path))
        {
            await formFile.CopyToAsync(fs);
            await fs.FlushAsync();
        }
        var url = $"Avatar/{saveName}";
        await _userRepository.UploadAvatar(uuid, url);
        await _userRepository.SaveAsync();
        return Ok(new { code = 200, message = "上传成功" });
    }

    [HttpPost]
    public async Task<IActionResult> UploadAvatars(IFormFile formFile)
    {
        var fileSize = formFile.Length;
        if (fileSize > 1024 * 1024 * 2) //2M TODO:(1mb=1024X1024b)
        {
            return Ok(new { code = 0, message = "上传的文件不能大于5M" });
        }
        var currentDate = DateTime.Now;
        var fileExtension = Path.GetExtension(formFile.FileName);//获取文件格式，拓展名
        var saveName = currentDate.ToString("yyMMddHHmmss") + currentDate.Millisecond.ToString() + fileExtension;
        string web_path = _webHostEnvironment.WebRootPath;
        string folderPath = Path.Combine("wwwroot", "Avatar");

        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }
        string path = Path.Combine(folderPath, saveName);
        using (var fs = System.IO.File.Create(path))
        {
            await formFile.CopyToAsync(fs);
            await fs.FlushAsync();
        }
        var url = $"Avatar/{saveName}";
        return Ok(new { code = 200, message = "上传成功", data = url });
    }
    /// <summary>
    /// 上传培训文件
    /// </summary>
    /// <param name="formFile"></param>
    /// <returns></returns>
    [HttpPost]
    [DisableRequestSizeLimit]
    public async Task<IActionResult> UploadTrainFiles(IFormFile formFile)
    {
        //var fileSize = formFile.Length;
        //if (fileSize > 1024 * 1024 * 2) //2M TODO:(1mb=1024X1024b)
        //{
        //    return Ok(new { code = 0, message = "上传的文件不能大于5M" });
        //}
        //string[] validExtensions = { "ppt", "doc", "docx", "pptx", "xls", "xlsx" };
        string[] validExtensions = { "ppt", "pptx", "doc" };
        string fileExtension = Path.GetExtension(formFile.FileName)?.TrimStart('.');
        var train = await _trainRepository.UnderwayTrain();
        if (train == null)
        {
            return Ok(new { ret = false, code = 200, message = "无正在进行的培训" });
        }

        if (validExtensions.Contains(fileExtension, StringComparer.OrdinalIgnoreCase) == true)
        {
            string FolderPath = Path.Combine("wwwroot", "Train", DateTime.Now.ToString("yyMMdd"), train.Name);
            if (!Directory.Exists(FolderPath))
            {
                Directory.CreateDirectory(FolderPath);
            }
            string apaths = Path.Combine(FolderPath, formFile.FileName.Replace(fileExtension, "")) + "pdf";
            UploadFileRepository.ConvertDocumentToPdf(fileExtension, formFile, apaths);
        }

        string folderPath = Path.Combine("wwwroot", "Train", DateTime.Now.ToString("yyMMdd"), train.Name);
        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }

        if (String.IsNullOrEmpty(train.Files))
        {

            List<Dictionary<string, string>> fileArray = new List<Dictionary<string, string>>();
            Dictionary<string, string> item = new Dictionary<string, string>
            {    {"name",formFile.FileName},
                 {"url",$"Train/{DateTime.Now.ToString("yyMMdd")}/{train.Name}/{formFile.FileName}"},
                 {"type",formFile.ContentType}
            };
            fileArray.Add(item);
            string json = JsonConvert.SerializeObject(fileArray);
            _trainRepository.UpdetaFiles(json);
            string path = Path.Combine(folderPath, formFile.FileName);
            using (var fs = System.IO.File.Create(path))
            {
                await formFile.CopyToAsync(fs);
                await fs.FlushAsync();
            }
            return Ok(new { code = 200, message = "上传成功", data = json });
        }
        var trainFile = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(train.Files);

        Dictionary<string, string> items = new Dictionary<string, string>
            {
                 {"name",formFile.FileName},
                 {"url",$"Train/{DateTime.Now.ToString("yyMMdd")}/{train.Name}/{formFile.FileName}"},
                 {"type",formFile.ContentType}
            };
        trainFile.Add(items);
        string file = JsonConvert.SerializeObject(trainFile);
        _trainRepository.UpdetaFiles(file);
        string paths = Path.Combine(folderPath, formFile.FileName);
        using (var fs = System.IO.File.Create(paths))
        {
            await formFile.CopyToAsync(fs);
            await fs.FlushAsync();
        }
        return Ok(new { code = 200, message = "上传成功", data = file });
    }

    //[HttpPost]
    //[DisableRequestSizeLimit]
    //public async Task<IActionResult> UploadVideoFiles(IFormFile formFile, [FromQuery] string type)
    //{

    //    var train = await _trainRepository.UnderwayTrain();
    //    if (train == null)
    //    {
    //        return Ok(new { ret = false, code = 200, message = "无正在进行的培训" });
    //    }
    //    string folderPath = Path.Combine("wwwroot", "Train", DateTime.Now.ToString("yyMMdd"), train.Name);

    //    if (!Directory.Exists(folderPath))
    //    {
    //        Directory.CreateDirectory(folderPath);
    //    }
    //    string path = Path.Combine(folderPath, formFile.FileName);

    //    var list = _trainRepository.SaveVideo($"Train/{DateTime.Now.ToString("yyMMdd")}/{train.Name}/{formFile.FileName}", type);
    //    using (var fs = System.IO.File.Create(path))
    //    {
    //        await formFile.CopyToAsync(fs);
    //        await fs.FlushAsync();
    //    }
    //    return Ok(new { code = 200, message = "上传成功", data = list });
    //}
    /// <summary>
    /// 上传培训文件
    /// </summary>
    /// <param name="formFile"></param>
    /// <returns></returns>
    [HttpPost]
    [DisableRequestSizeLimit]
    public async Task<IActionResult> UploadMeetingFiles(IFormFile formFile)
    {
        //var fileSize = formFile.Length;
        //if (fileSize > 1024 * 1024 * 2) //2M TODO:(1mb=1024X1024b)
        //{
        //    return Ok(new { code = 0, message = "上传的文件不能大于5M" });
        //}
        //string[] validExtensions = { "ppt", "doc", "docx", "pptx", "xls", "xlsx" };
        string[] validExtensions = { "ppt", "pptx", "doc" };
        string fileExtension = Path.GetExtension(formFile.FileName)?.TrimStart('.');
        var train = await _meetingRepository.UnderwayTrain();
        if (train == null)
        {
            return Ok(new { ret = false, code = 200, message = "无正在进行的培训" });
        }

        if (validExtensions.Contains(fileExtension, StringComparer.OrdinalIgnoreCase) == true)
        {
            string FolderPath = Path.Combine("wwwroot", "Meeting", DateTime.Now.ToString("yyMMdd"), train.Name);
            if (!Directory.Exists(FolderPath))
            {
                Directory.CreateDirectory(FolderPath);
            }
            string apaths = Path.Combine(FolderPath, formFile.FileName.Replace(fileExtension, "")) + "pdf";
            UploadFileRepository.ConvertDocumentToPdf(fileExtension, formFile, apaths);
        }

        string folderPath = Path.Combine("wwwroot", "Meeting", DateTime.Now.ToString("yyMMdd"), train.Name);
        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }

        if (String.IsNullOrEmpty(train.Files))
        {

            List<Dictionary<string, string>> fileArray = new List<Dictionary<string, string>>();
            Dictionary<string, string> item = new Dictionary<string, string>
            {    {"name",formFile.FileName},
                 {"url",$"Meeting/{DateTime.Now.ToString("yyMMdd")}/{train.Name}/{formFile.FileName}"},
                 {"type",formFile.ContentType}
            };
            fileArray.Add(item);
            string json = JsonConvert.SerializeObject(fileArray);
            _meetingRepository.UpdetaFiles(json);
            string path = Path.Combine(folderPath, formFile.FileName);
            using (var fs = System.IO.File.Create(path))
            {
                await formFile.CopyToAsync(fs);
                await fs.FlushAsync();
            }
            return Ok(new { code = 200, message = "上传成功", data = json });
        }
        var trainFile = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(train.Files);

        Dictionary<string, string> items = new Dictionary<string, string>
            {
                 {"name",formFile.FileName},
                 {"url",$"Meeting/{DateTime.Now.ToString("yyMMdd")}/{train.Name}/{formFile.FileName}"},
                 {"type",formFile.ContentType}
            };
        trainFile.Add(items);
        string file = JsonConvert.SerializeObject(trainFile);
        _meetingRepository.UpdetaFiles(file);
        string paths = Path.Combine(folderPath, formFile.FileName);
        using (var fs = System.IO.File.Create(paths))
        {
            await formFile.CopyToAsync(fs);
            await fs.FlushAsync();
        }
        return Ok(new { code = 200, message = "上传成功", data = file });
    }

    //[HttpPost]
    //[DisableRequestSizeLimit]
    //public async Task<IActionResult> UploadMeetingVideoFiles(IFormFile formFile, [FromQuery] string type)
    //{

    //    var train = await _meetingRepository.UnderwayTrain();
    //    if (train == null)
    //    {
    //        return Ok(new { ret = false, code = 200, message = "无正在进行的培训" });
    //    }
    //    string folderPath = Path.Combine("wwwroot", "Meeting", DateTime.Now.ToString("yyMMdd"), train.Name);

    //    if (!Directory.Exists(folderPath))
    //    {
    //        Directory.CreateDirectory(folderPath);
    //    }
    //    string path = Path.Combine(folderPath, formFile.FileName);

    //    var list = _meetingRepository.SaveVideo($"Meeting/{DateTime.Now.ToString("yyMMdd")}/{train.Name}/{formFile.FileName}", type);
    //    using (var fs = System.IO.File.Create(path))
    //    {
    //        await formFile.CopyToAsync(fs);
    //        await fs.FlushAsync();
    //    }
    //    return Ok(new { code = 200, message = "上传成功", data = list });
    //}
}